# -*- coding:utf-8 -*-
from com.zzh.utils.dbUtils import MysqlUtils
from com.zzh.utils.table2Json_v2 import Table2JsonByYM
from com.zzh.utils.requestFieldMapDBField import requestFieldMapToDBField_YM
from com.zzh.utils.sqlUtils.SqlUtils import SqlUtils
from com.zzh.utils.jsonUtils_v2.table2Json_YM import Table2JsonYM
from AuthTokenOperation import authTokenOperation
from com.zzh.utils import generate_code

import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)
import time
from datetime import datetime

localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


class UserDao(object):
    def __init__(self):
        self.conn = MysqlUtils.get_mysql_connections_v2()

    def selectUser(self, id):
        """
        根据ID查询信息，返回元组

        """
        sql = "select * from zzh_user WHERE user_id=%s"

        cur = self.conn.cursor()
        rs = cur.execute(sql, [id])
        arr = cur.fetchone()
        cur.close()
        self.conn.close()
        return arr

    def queryUserById(self, userId):
        """
        根据ID查询信息    查询    zzh_user
        :param :
        :return:
        单体查询，按照id查询
        """
        sql = "SELECT * FROM view_user WHERE user_id=%s"
        cur = self.conn.cursor()
        total_count = cur.execute(sql,[userId])
        if total_count:
            result = cur.fetchall()
            cur.close()
            self.conn.close()
            userOauthJson = Table2JsonYM.viewUser_list_to_json(result)
            return total_count, userOauthJson
        else:
            cur.close()
            self.conn.close()
            return 0, None


    def queryUserNameById(self, userId):
        """
        根据ID查询信息    查询    zzh_user
        :param :
        :return:
        单体查询，按照id查询
        """
        sql = "SELECT user_name FROM zzh_user WHERE user_id=%s"
        cur = self.conn.cursor()
        total_count = cur.execute(sql, [userId])
        return total_count



    def queryUserByCondition(self, **kwargs):
        conditions = kwargs['conditions']
        multiSort = kwargs['multiSort']
        page_index = kwargs['pageIndex']
        PAGE_SIZE = kwargs['pageSize']

        fieldMap = requestFieldMapToDBField_YM.userMap#要改的这个
        whereSentence = SqlUtils.getOption(conditions, fieldMap)

        cur = self.conn.cursor()
        if multiSort:
            # 排序拼接
            sortRule = SqlUtils.getSortRule(multiSort, fieldMap)
            sql = "SELECT * FROM zzh_user WHERE " + whereSentence + " ORDER BY " + sortRule
        else:
            sql = "SELECT * FROM zzh_user WHERE " + whereSentence


        total_count = cur.execute(sql)
        if total_count:
            result = cur.fetchall()
            cur.close()
            self.conn.close()
            if (page_index * PAGE_SIZE) < total_count:
                start = (page_index - 1) * PAGE_SIZE
                end = page_index * PAGE_SIZE
                userOauthPart = result[start: end]
                userOauthJSON = Table2JsonByYM.user_list_to_json(userOauthPart)
                return total_count, userOauthJSON
            else:
                start = (page_index - 1) * PAGE_SIZE
                userOauthPart = result[start: ]
                userOauthJSON = Table2JsonByYM.user_list_to_json(userOauthPart)
                return total_count, userOauthJSON

        else:
            cur.close()
            self.conn.close()
            return 0, None


    def addUser(self,Info):
        """

        :param userRechargeInfo:
        :return:
        """

        userName = Info['userName']  #
        userSalt = Info['userSalt']
        userPassword = Info['userPassword']  #
        userPhone = Info['userPhone']
        userEmail = Info['userEmail']#
        userAvatar = Info['userAvatar']  #
        userNickName = Info['userNickName']

        userStatus = Info['userStatus']#
        userRegTime = localTime  #
        userRegIp = Info['userRegIp']



        cur = self.conn.cursor()
        sql = 'INSERT INTO zzh_user (user_name, user_salt, user_password, user_phone, user_email, user_avatar,user_nick_name,user_status,user_reg_time,user_reg_ip) VALUES (%s,%s,%s, %s ,%s, %s, %s,%s, %s,%s)'
        rs=cur.execute(sql,[userName,userSalt,userPassword,userPhone,userEmail,userAvatar,userNickName,userStatus,userRegTime,userRegIp])
        self.conn.commit()

        sql2 = 'SELECT max(user_id) FROM zzh_user'
        rs2TC = cur.execute(sql2)
        rs2 = cur.fetchone()
        rs2Int = rs2[0]

        sql3 = "SELECT * FROM zzh_user WHERE user_id=%s"
        cur = self.conn.cursor()
        total_count = cur.execute(sql3, [rs2Int])
        if total_count:
            result = cur.fetchall()
            cur.close()
            self.conn.close()
            userOauthJson = Table2JsonByYM.user_list_to_json(result)
            return total_count, userOauthJson
        else:
            cur.close()
            self.conn.close()
            return 0, None



    def updateUser(self,Info):#

        userId = Info['userId']  # 必填，请传递user_id
        userName = Info['userName']  #
        userSalt = Info['userSalt']
        userPassword = Info['userPassword']  #
        userPhone = Info['userPhone']
        userEmail = Info['userEmail']#
        userAvatar = Info['userAvatar']  #
        userNickName = Info['userNickName']
        userStatus = Info['userStatus']#


        cur = self.conn.cursor()
        sql = 'UPDATE zzh_user SET user_name=%s, user_salt=%s, user_password=%s, user_phone=%s, user_email=%s, user_avatar=%s,user_nick_name=%s,user_status=%s WHERE user_id=%s'
        rs=cur.execute(sql,[userName,userSalt,userPassword,userPhone,userEmail,userAvatar,userNickName,userStatus,userId])
        self.conn.commit()
        cur.close()
        self.conn.close()
        if rs:
            return rs
        else:
            return None

    def deleteUser(self, ids):
        """
        根据ID删除数据表信息，ID需要以数组形式传递
        :param adminIdArray: id 构成的数组 []
        :return:
        """
        sql = "delete from zzh_user WHERE user_id=%s"
        cur = self.conn.cursor()
        for id in ids:
            rs = cur.execute(sql, [id])
        self.conn.commit()
        cur.close()
        self.conn.close()
        return rs

    # 判断手机号是否注册
    def is_regist(self, phone):
        cur = self.conn.cursor()

        sql = "select * from zzh_user WHERE user_phone=%s"
        rs = cur.execute(sql, [phone])
        cur.close()
        self.conn.close()

        return rs

    # 用户注册
    def regist_user(self, user_info):
        userPhone = user_info['login_phone']
        userName = userPhone
        userPassword = user_info['login_pwd']
        userRegIP = user_info['userRegIP']
        userRegTime = user_info['userRegTime']
        #invitedCode = user_info['invitedCode'] #后台随机生成
        invitedCode = generate_code.generate_verification_code2()

        cur = self.conn.cursor()
        sql = "insert into zzh_user (user_name,user_password,user_phone,user_reg_time,user_reg_ip) " \
              " VALUES (%s,%s,%s,%s,%s) "
        result = cur.execute(sql, [userName, userPassword, userPhone, userRegTime, userRegIP])
        self.conn.commit()

        if result:
            token = authTokenOperation().generateToken(userPhone, userPassword)
            sql2 = "select max(user_id) from zzh_user"
            rs = cur.execute(sql2)
            idn = cur.fetchall()
            newId = idn[0][0]
            memberExpired = datetime.date(datetime.strptime("1900-01-01", "%Y-%m-%d"))
            sql3 = "insert into zzh_member (user_id, invited_code, member_expired) VALUES (%s, %s, %s)"
            rs3 = cur.execute(sql3, [newId, invitedCode, memberExpired])
            self.conn.commit()
            cur.close()
            self.conn.close()
            return newId, token
        else:
            cur.close()
            self.conn.close()
            return 0, None

    '''用户登录验证'''

    def user_login(self, loginPhone, password):
        cur = self.conn.cursor()
        sql = "select user_password from zzh_user where user_phone=%s"
        result = cur.execute(sql, [loginPhone])
        if not result:
            return 0, None  # 0-用户不存在
        else:
            login_reult = cur.fetchall()
            pwd = login_reult[0][0]
            if (pwd == password):
                sql = "select *  from view_user WHERE user_phone=%s"
                rs = cur.execute(sql, [loginPhone])
                user_list = cur.fetchall()
                userJson = Table2JsonYM.viewUser_list_to_json(user_list)
                cur.close()
                self.conn.close()
                return 1, userJson  # 登陆成功
            else:
                return -1, None  # 密码不正确，登陆失败


    '''重置密码'''
    def reset_passwd(self, new_pwd, phone):
        cur = self.conn.cursor()
        sql = "update zzh_user set user_password=%s where user_phone=%s"
        result = cur.execute(sql, [new_pwd, phone])
        self.conn.commit()

        cur.close()
        self.conn.close()
        return result

    def update_passwd(self, user_id, oldPwd, newPwd):
        """
        修改密码
        :param user_id:
        :param oldPwd:
        :param newPwd:
        :return:
        """
        cur = self.conn.cursor()
        sql = "select user_password from zzh_user WHERE user_id=%s"
        rs = cur.execute(sql, [user_id])
        result = cur.fetchall()
        pwd = result[0][0]
        if (oldPwd == pwd):
            sql = "update zzh_user set user_password=%s where user_id=%s"
            rs = cur.execute(sql, [newPwd, user_id])
            self.conn.commit()
            cur.close()
            self.conn.close()
            if rs:
                return 1
            else:
                return 0
        else:
            return -1